/**
 * 
 */
package cz.geoserver.KMLpublisher.servlet;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.Map;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cz.geoserver.KMLpublisher.db.SQLExecutor;
import cz.geoserver.KMLpublisher.util.ServletUtil;

/**
 * Servlet that starts processing of input client's requests 
 * According to combination of parameters calls utility that processes whole request.
 * Mandatory parameters in combination:
 * 1. query
 * 2. sqlId & bbox
 * 3. query & bbox
 * 4. data_table & clustered_att & query
 * 5. data_table & clustered_att & query & bbox
 * @author mkepka
 *
 */
public class DynamicKMLServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    /**
     * Arrays with possible forms of parameters 
     */
    private static String[] parBBOX = {"BBOX", "bbox", "Bbox"};
    private static String[] parQuery = {"QUERY", "query", "Query"};
    private static String[] parSqlId = {"SQLID","sqlId", "SQL_ID", "sql_id", "SqlId"};
    private static ServletUtil sUtil;

    /**
     * Methods sets database connection parameters in initial phase of Servlet 
     * and creates an instance of utility for further request processing
     */
    @Override
    public void init() throws ServletException {
        try {
        //setting connection to DB
            String propFile = getClass().getResource("database.properties").getFile();
            Properties prop = new Properties();
            prop.load(new FileInputStream(propFile));
            SQLExecutor.setProperties(prop);
        }catch (IOException e) {
            e.printStackTrace();
        }
        // creating instance of ServletUtility with info that it is created from servlet
        sUtil = new ServletUtil(true);
    }

    /**
     * Method processes GET request by sending it to POST method.
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

	/**
	 * Method processes request if there is any combination of parameters that enables further processing. 
	 * If not sends back to client an exception.
	 */
	@Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // Trying to find possible parameters in GET request
        Map paramMap = req.getParameterMap();
        String queryPar = sUtil.findParameterName(parQuery, paramMap);
        String bboxPar = sUtil.findParameterName(parBBOX, paramMap);
        String sesIdPar = sUtil.findParameterName(parSqlId, paramMap);
        
        try{
           // if there is any combination of parameter: query or both parameters sqlId and bbox in request
           if(!queryPar.isEmpty() || (!sesIdPar.isEmpty() && !bboxPar.isEmpty())){
               
               sUtil.processRequest(req, resp);
           }
           // if there is not any known parameter in request
           else{
               resp.setContentType("text/html");
               resp.setStatus(400);
               PrintWriter pw = resp.getWriter();
               pw.write("Request does not contain required combination of parameters!");
           }	
        } catch(SQLException e){
            resp.setContentType("text/html");
            resp.setStatus(400);
            PrintWriter pw = resp.getWriter();
            pw.write(e.getMessage());
        }
    }
}